import request from "./request"
import { getSysParam, showModal, showModalPromise } from "@/utils/index"
import { userActionType } from "@/store/modules/user"
import store from "@/store"

export default {
  handlePay(params) {
    return new Promise(async (resolve, reject) => {
      uni.showLoading({
        title: "加载中",
        mask: true,
      })
      //检查是否有开启ios支付，关闭了ios支付则ios不允许支付
      if (!(await this.checkIosPay())) {
        uni.hideLoading()
        reject("根据相关政策，ios暂不提供此服务")
        return
      }
      //获取支付所需要的参数
      const dataRes = await request({
        url: "ord/Pay",
        errorHandle: true,
        data: {
          businessId: params.businessId,
          ordNo: params.ordNo,
          type: params.type,
          tradeType: params.tradeType,
        },
      })
      //不需要支付，直接返回支付成功
      if (dataRes.needPay === "0") {
        uni.hideLoading()
        resolve()
        return
      }
      uni.hideLoading()
      //调用微信api发起支付
      uni.requestPayment({
        provider: "wxpay",
        timeStamp: dataRes.timeStamp,
        nonceStr: dataRes.nonceStr,
        package: dataRes.package,
        signType: dataRes.signType,
        paySign: dataRes.paySign,
        success: function (res) {
          uni.showLoading({
            title: "加载中",
            mask: true,
          })
          //发起轮询，每隔一秒检查一遍支付结果
          let maxLoop = 10
          let loop = 0
          let that = this
          async function checkPayment() {
            loop++
            //超过最大轮询次数，停止轮询
            if (loop >= maxLoop) {
              uni.hideLoading()
              showModalPromise({
                title: "提示",
                content: "订单正在处理中，如有问题请联系客服",
                showCancel: false,
              })
              reject()
              return
            }
            //轮询的接口
            const res = await request({
              url: "ord/getPayResult",
              errorHandle: true,
              data: {
                ordNo: params.ordNo,
              },
            })
            //检查是否支付成功
            if (res.ordStatus !== "WaitPay") {
              //刷新用户信息
              await store.dispatch(userActionType.action.refreshUserInfo)
              uni.hideLoading()
              resolve(res)
              return
            } else {
              setTimeout(checkPayment, 2000)
            }
          }
          setTimeout(checkPayment, 2000)
        },
        fail: function (err) {
          console.log(err, "err")
          reject("您已取消支付")
        },
      })
    })
  },
  //检测是否关闭了ios支付且当前设备为ios，其中开启了ios支付或者不是ios设备的情况下，返回true，否则返回false
  async checkIosPay() {
    const systemInfo = uni.getSystemInfoSync()
    if (systemInfo.platform.toLowerCase() === "ios" && (await getSysParam("openIosPay")) === "否") {
      return false
    }
    return true
  },
}
